var photoMarker = null;
var map = null;
var searchBox;
var infowindow = new google.maps.InfoWindow({
    content: "<b>Me arraste</b>"
});

function init_map(lat, lng) {
	var setMapNull = false;
	if(!lat || !lng){
		setMapNull = true;
		lat=0; lng=0;
	}
    var myOptions = {
        zoom: (setMapNull?1:14),
        center: new google.maps.LatLng(lat, lng),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        panControl: false,
        zoomControl: true,
        zoomControlOptions: {
        		position: google.maps.ControlPosition.LEFT_CENTER,
        		style: google.maps.ZoomControlStyle.LARGE
        		},
        mapTypeControl: false,
        streetViewControl: false
    };
    map = new google.maps.Map(document.getElementById("gmap_canvas"), myOptions);
    photoMarker = new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(lat, lng)
    });
    
    var input_small = (document.getElementById('pac-input'));
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input_small);

    searchBox = new google.maps.places.SearchBox((input_small));
    
    google.maps.event.addListener(searchBox, 'places_changed', function() {
		var results = searchBox.getPlaces();
		
		if(results && results.length>0){
			if(photoMarker.draggable){
				photoMarker.setPosition(results[0].geometry.location);
			}
			var latLngBounds = results[0].geometry.bounds;
			if(!latLngBounds) latLngBounds = results[0].geometry.viewport;
			if(latLngBounds){
				map.fitBounds(latLngBounds);
			}else{
				map.setCenter(results[0].geometry.location);
				map.setZoom(15);
			}
		}
    });
    
    if(setMapNull) photoMarker.setMap(null);
}

function editLocation(){
	
	if(photoMarker.draggable){
		var coord = photoMarker.getPosition();
		var photoid = document.getElementById("currentPhotoid").value;
		var urlAdd = "./add_location.php?latitude="+coord.lat()+"&longitude="+coord.lng()+"&photoid="+photoid;
		alert(urlAdd);
		$.ajax({
			url: urlAdd,
			type: "GET",
			dataType: "json",
			async: false,
			success: function(data) {
				if(data.status){
					document.getElementById("locationButton").innerHTML = ('Alterar Localização');
					photoMarker.setDraggable(false);
					infowindow.close();
				}else{
					alert("Não foi possível salvar a localização.");
				}
			},
			error: function(data) {
				console.log(data);
			}
		});
	}else{
		photoMarker.setPosition(map.getCenter());
		photoMarker.setMap(map);
		photoMarker.setDraggable(true);
		
	    infowindow.open(map, photoMarker);
	    document.getElementById("locationButton").innerHTML = ('Salvar Localização');
	}
}
//google.maps.event.addDomListener(window, 'load', init_map);